import 'dart:async';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flutter_sound/public/flutter_sound_recorder.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zootix/screens/chat/zt_private_chat.controller.dart';
import 'package:zootix/util/zt_screen_adaper_util.dart';
import 'package:audio_session/audio_session.dart';
import 'package:zootix/util/zt_snack_bar.util.dart';
import 'package:zootix/zt_app_theme.dart';
import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';

class BuildMic extends StatefulWidget {
  @override
  _BuildMicState createState() => _BuildMicState();
}

class _BuildMicState extends State<BuildMic>
    with SingleTickerProviderStateMixin {
  final _controller = Get.find<ZtPrivateChatController>();
  @override
  void initState() {
    super.initState();
    _controller.micAnimationController = AnimationController(
      duration: Duration(seconds: _controller.maxRecordTime),
      vsync: this,
    );
  }

  @override
  void dispose() {
    _controller.micAnimationController?.dispose();
    _controller.micAnimationController = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ZtPrivateChatController>(builder: (_) {
      return GestureDetector(
          onLongPressDown: (_) async {
            if (await Permission.microphone.isGranted) {
              if (!_controller.mRecorderIsInited.value) {
                await _controller.initRecorder();
              }
              final func = _controller.uploadFilePath.isNotEmpty
                  ? _controller.getPlaybackFn()
                  : _controller.getRecorderFn();
              func!();
              return;
            }
            final status = await Permission.microphone.request();
            if (status != PermissionStatus.granted) {
              ZtSnackBarUtil()
                  .warning("Please enable microphone permission to use mic");
            } else {}
          },
          onLongPressUp: () {
            if (_controller.uploadFilePath.isEmpty) {
              _controller.stopRecorder();
            }
          },
          child: Stack(
            alignment: Alignment.center,
            children: [
              if (_controller.micAnimationController != null)
                Container(
                    decoration: BoxDecoration(
                        color: _controller.mRecorder!.isRecording
                            ? Color.fromARGB(255, 238, 238, 238)
                            : Color(0xFFF7F8FA),
                        borderRadius: BorderRadius.circular(100)),
                    width: 120,
                    height: 120,
                    child: AnimatedBuilder(
                      animation: _controller.micAnimationController!,
                      builder: (BuildContext context, Widget? child) {
                        return CustomPaint(
                          painter: CirclePainter(
                            progress: _controller.micAnimationController!.value,
                            isDrawing: _controller.isDrawing.value,
                          ),
                        );
                      },
                    )),
              _controller.uploadFilePath.isNotEmpty
                  ? Icon(
                      _controller.mPlayer!.isPlaying
                          ? Icons.pause
                          : Icons.play_arrow_rounded,
                      size: ZtScreenAdaper.sp(60))
                  : Icon(
                      (_controller.mRecorder!.isRecording ||
                              _controller.uploadFilePath.isEmpty)
                          ? Icons.mic_none
                          : Icons.play_arrow_rounded,
                      size: ZtScreenAdaper.sp(60),
                    )
            ],
          ));
    });
  }
}

class CirclePainter extends CustomPainter {
  final double progress;
  final bool isDrawing;

  CirclePainter({required this.progress, required this.isDrawing});

  @override
  void paint(Canvas canvas, Size size) {
    final double centerX = size.width / 2;
    final double centerY = size.height / 2;
    final double radius = size.width / 2;

    final double angle = 2 * pi * progress;

    final Paint paint = Paint()
      ..color = ZtAppTheme.primaryColor
      ..strokeWidth = 6.0
      ..style = PaintingStyle.stroke;

    final Path path = Path();
    path.addArc(
      Rect.fromCircle(center: Offset(centerX, centerY), radius: radius),
      -pi / 2,
      angle,
    );

    if (!isDrawing) {
      path.reset();
    }
    canvas.drawPath(path, paint);
    // if (!isDrawing) {
    //   canvas.drawCircle(Offset(centerX, centerY), radius, paint);
    // }
  }

  @override
  bool shouldRepaint(CirclePainter oldDelegate) =>
      oldDelegate.progress != progress || oldDelegate.isDrawing != isDrawing;
}
